package com.microservice.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.microservice.wechat.entity.dto.MediaUploadResponse;
import com.microservice.wechat.service.WechatMediaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

/**
 * 微信素材管理服务实现类
 */
@Slf4j
@Service
public class WechatMediaServiceImpl implements WechatMediaService {
    
    @Autowired
    private RestTemplate restTemplate;
    
    private static final String MEDIA_UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={accessToken}&type={type}";
    private static final String MEDIA_UPLOAD_URL_SHORT_TIME = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={accessToken}&type={type}";

    @Override
    public MediaUploadResponse uploadMedia(MultipartFile file, String type, String accessToken) {
        try {
            log.info("调用微信上传素材接口，文件名: {}, 类型: {}, accessToken: {}", 
                    file.getOriginalFilename(), type, accessToken);
            
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            
            // 构建multipart表单数据
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            
            // 将MultipartFile转换为ByteArrayResource
            ByteArrayResource fileResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };
            
            body.add("media", fileResource);
            
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            
            // 发送请求，使用ResponseEntity获取原始响应
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(
                MEDIA_UPLOAD_URL,
                requestEntity,
                String.class,
                accessToken,
                type
            );
            
            // 手动解析JSON响应
            String responseBody = responseEntity.getBody();
            log.info("微信上传素材接口原始响应: {}", responseBody);
            
            MediaUploadResponse response = JSON.parseObject(responseBody, MediaUploadResponse.class);

            log.info("微信上传素材接口解析后响应: {}", response);
            
            return response;
        } catch (Exception e) {
            log.error("调用微信上传素材接口异常", e);
            MediaUploadResponse errorResponse = new MediaUploadResponse();
            errorResponse.setErrcode(-1);
            errorResponse.setErrmsg("上传文件异常: " + e.getMessage());
            return errorResponse;
        }
    }

    @Override
    public MediaUploadResponse uploadMediaId(MultipartFile file, String type, String accessToken) {
        try {
            log.info("调用微信上传临时素材接口，文件名: {}, 类型: {}, accessToken: {}",
                    file.getOriginalFilename(), type, accessToken);

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            // 构建multipart表单数据
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();

            // 将MultipartFile转换为ByteArrayResource
            ByteArrayResource fileResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };

            body.add("media", fileResource);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 发送请求，使用ResponseEntity获取原始响应
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(
                    MEDIA_UPLOAD_URL_SHORT_TIME,
                    requestEntity,
                    String.class,
                    accessToken,
                    type
            );

            // 手动解析JSON响应
            String responseBody = responseEntity.getBody();
            log.info("微信上传临时素材接口原始响应: {}", responseBody);

            MediaUploadResponse response = JSON.parseObject(responseBody, MediaUploadResponse.class);

            log.info("微信上传临时素材接口解析后响应: {}", response);

            return response;
        } catch (Exception e) {
            log.error("调用微信上传临时素材接口异常", e);
            MediaUploadResponse errorResponse = new MediaUploadResponse();
            errorResponse.setErrcode(-1);
            errorResponse.setErrmsg("上传文件异常: " + e.getMessage());
            return errorResponse;
        }
    }
}
